<template>
  <div>
    <el-button @click="oepnDialog" style="width: 200px; margin-left: 8px; margin-bottom: 10px"
      >内容模糊检索</el-button
    >
    <el-dialog
      title="一键查询"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="handleClose"
    >
      <div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="检索内容">
            <el-input
              v-model="form.search_str"
              size="small"
              style="width: 600px; margin-right: 10px"
              placeholder="请输入内容"
              @keyup.enter.native="findLinkFile"
            ></el-input>
            <el-button size="small" type="primary" @click="findLinkFile">检索</el-button>
            <el-button size="small" @click="queryList = []">清空</el-button>
          </el-form-item>
          <el-form-item label="目录范围">
            <el-tree
              :data="treeData"
              ref="treeRef"
              node-key="id"
              show-checkbox
              default-expand-all
              @check-change="handleCheckChange"
              :expand-on-click-node="false"
              :current-node-key="form.folder_ids"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span style="margin-right: 20px">{{ node.label }}</span>
              </span>
            </el-tree>
          </el-form-item>
          <el-form-item label="文档范围">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="文档列表" name="1">
                <el-checkbox-group v-model="form.file_ids">
                  <el-checkbox
                    v-for="item in partition_namesList"
                    :key="item.id"
                    :label="item.id"
                    :name="item.id"
                    >{{ item.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-collapse-item>
            </el-collapse>
          </el-form-item>
        </el-form>
        <h3>相关文件</h3>
        <el-table :data="queryList" size="small" border v-loading="loading">
          <el-table-column prop="file_name" label="文件名称" width="150"></el-table-column>
          <el-table-column prop="page_content" label="内容">
            <template slot-scope="scope">
              <p v-html="scope.row.page_content"></p>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="view(scope.row.file_id, 'file', scope.row.file_name)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getData, postData } from '@/service/getData';

export default {
  data() {
    return {
      dialogVisible: false,
      treeData: [],
      activeNames: [],
      limitFileList: [
        {
          name: '市场',
          role: [
            '周百夷',
            '李京姝',
            '超级管理员1',
            '王建坤',
            '王进才',
            '王伟-山东交控',
            '张明静',
            '周大鹏',
            '张志政',
            '毕明荣',
            '高凯',
            '郭恒铭',
            '谷宇',
            '黄超',
            '黄健',
            '金江',
            '梁材国',
            '李春明',
            '麻吉泉',
            '谭剑雪',
          ],
        },
      ],
      loading: false,
      // 表单数据
      form: {
        search_str: '',
        folder_ids: [],
        file_ids: [],
      },
      queryList: [], // 查询结果列表
      partition_namesList: [], // 检索范围列表
    };
  },

  mounted() {
    this.getTree();
    // this.calcData(); // 计算数据
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      this.form.file_ids = []; // 清空已选择的节点
      const tree = this.$refs.treeRef;
      if (tree) {
        let arr = [];
        let selectedNodes = []; // 获取所有选中的节点
        let nodes = [];
        tree.getCheckedNodes().forEach((item) => {
          arr.push(item.id); // 获取所有选中节点的id
          if (item.files.length > 0) {
            item.files.forEach((item) => {
              nodes.push({
                name: item.name,
                id: item.id,
              }); // 获取所有选中节点的对象
              selectedNodes.push(item.id); // 获取所有选中节点的id
            });
          }
          nodes.push(); // 获取所有选中节点的对象
        });
        this.form.folder_ids = arr; // 更新已选择的节点
        this.form.file_ids = selectedNodes; // 更新已选择的节点
        this.partition_namesList = nodes;
      }
    },
    getTree() {
      getData('api/knowledge_base/folders/').then((res) => {
        this.treeData = res;
        // 递归遍历数组，给每个对象添加label属性
        const traverse = (arr) => {
          arr.forEach((item) => {
            item.label = item.name;
            if (item.children && item.children.length > 0) {
              traverse(item.children);
            }
          });
        };
        traverse(this.treeData);
      });
    },

    limitFile(value) {
      let returnValue = true;
      this.limitFileList.forEach((item) => {
        if (item.name === value) {
          // 判断数组中是否包含当前用户的名字 有就显示 没有就不显示
          if (!item.role.includes(this.$store.state.user.username)) {
            returnValue = false;
          }
        }
      });
      return returnValue;
    },
    view(id, type, name) {
      console.log(id, type, name);
      this.$emit('call-parent', id, type, name);
    },
    oepnDialog() {
      this.calcData();
      this.dialogVisible = true;
      this.form.folder_ids = []; // 清空已选择的节点
      this.form.file_ids = []; // 清空已选择的节点
      this.form.search_str = ''; // 清空检索内容
      this.queryList = []; // 清空查询结果列表
      this.$refs.treeRef.setCheckedKeys([]); // 清空已选择的节点
    },
    calcData() {
      this.partition_namesList = []; // 检索范围列表
      this.treeData.forEach((item) => {
        // 筛选出 基础知识库中的 二级目录
        if (item.collection_name === '文档知识库') {
          item.partitions.forEach((item) => {
            if (this.limitFile(item.partition_name)) {
              this.partition_namesList.push(item.partition_name);
            }
          });
        }
      });
      this.form.partition_names = this.partition_namesList; // 默认选中所有
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    findLinkFile() {
      if (!this.form.search_str) {
        this.$message({
          message: '请输入检索内容',
          type: 'warning',
        });
        return;
      }
      this.loading = true;
      this.queryList = []; // 清空查询结果列表
      // 查询相关文件
      postData(
        'api/knowledge_base/files/retrieve_file_content/',
        {
          ...this.form,
        },
        'post',
      )
        .then((res) => {
          this.queryList = res.references;
          this.loading = false;
          console.log(res);
        })
        .finally(() => {});
    },
  },
};
</script>
<style scoped>
.el-dialog__close {
  color: #666;
}
</style>
